package com.hkfrich.system.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hkfrich.common.constant.Constants;
import com.hkfrich.common.utils.DateUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hkfrich.common.utils.StringUtils;
import com.hkfrich.generator.utils.DictUtils;
import com.hkfrich.system.domain.SysDictData;
import com.hkfrich.system.domain.SysDictType;
import com.hkfrich.system.mapper.SysDictDataMapper;
import com.hkfrich.system.mapper.SysDictTypeMapper;
import com.hkfrich.system.service.SysDictTypeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 字典类型Service业务层处理
 * 
 * @author _Heishuai
 * @date 2022-09-15 00:22:11
 */
@Service
public class SysDictTypeServiceImpl extends ServiceImpl<SysDictTypeMapper, SysDictType> implements SysDictTypeService {

    Logger logger = LoggerFactory.getLogger(SysDictTypeServiceImpl.class);

    @Resource
    private SysDictTypeMapper sysDictTypeMapper;
    @Resource
    private SysDictDataMapper sysDictDataMapper;


    /**
     * 项目启动时，初始化字典到缓存
     */
    @PostConstruct
    public void init()
    {
        logger.info("--------------->初始化字典数据开始<----------------");
        loadingDictCache();
        logger.info("--------------->初始化字典数据完成<----------------");
    }


    /**
     * 清空字典缓存数据
     */
    @Override
    public void clearDictCache()
    {
        DictUtils.clearDictCache();
    }

    /**
     * 重置字典缓存数据
     */
    @Override
    public void resetDictCache()
    {
        clearDictCache();
        loadingDictCache();
    }

    @Override
    public void deleteDictTypeByIds(List<Long> list) {
        for (Long dictId : list)
        {
            SysDictType dictType = sysDictTypeMapper.selectById(dictId);
            if (sysDictDataMapper.countDictDataByType(dictType.getDictType()) > 0)
            {
                throw new RuntimeException(String.format("%1$s已分配,不能删除", dictType.getDictName()));
            }
            sysDictTypeMapper.deleteById(dictId);
            DictUtils.removeDictCache(dictType.getDictType());
        }
    }

    /**
     * 加载字典缓存数据
     */
    @Override
    public void loadingDictCache()
    {
        SysDictData dictData = new SysDictData();
        dictData.setStatus("0");
        QueryWrapper<SysDictData> query = Wrappers.query(dictData);
        Map<String, List<SysDictData>> dictDataMap = sysDictDataMapper.selectList(query).stream().collect(Collectors.groupingBy(SysDictData::getDictType));
        for (Map.Entry<String, List<SysDictData>> entry : dictDataMap.entrySet())
        {
            DictUtils.setDictCache(entry.getKey(), entry.getValue().stream().sorted(Comparator.comparing(SysDictData::getDictSort)).collect(Collectors.toList()));
        }
    }

    @Override
    public String checkDictTypeUnique(SysDictType sysDictType) {
        Long dictId = StringUtils.isNull(sysDictType.getDictId()) ? -1L : sysDictType.getDictId();
        SysDictType dictType = sysDictTypeMapper.checkDictTypeUnique(sysDictType.getDictType());
        if (StringUtils.isNotNull(dictType) && dictType.getDictId().longValue() != dictId.longValue())
        {
            return Constants.NOT_UNIQUE;
        }
        return Constants.UNIQUE;
    }

    @Override
    public int updateDictType(SysDictType sysDictType) {
        SysDictType oldDict = sysDictTypeMapper.selectById(sysDictType.getDictId());
        sysDictDataMapper.updateDictDataType(oldDict.getDictType(), sysDictType.getDictType());
        int row = sysDictTypeMapper.updateById(sysDictType);
        if (row > 0)
        {
            List<SysDictData> dictDatas = sysDictDataMapper.selectDictDataByType(sysDictType.getDictType());
            DictUtils.setDictCache(sysDictType.getDictType(), dictDatas);
        }
        return row;
    }


    @Override
    public List<SysDictData> selectDictDataByType(String dictType) {
        List<SysDictData> dictDatas = DictUtils.getDictCache(dictType);
        if (StringUtils.isNotEmpty(dictDatas))
        {
            return dictDatas;
        }
        dictDatas = sysDictDataMapper.selectDictDataByType(dictType);
        if (StringUtils.isNotEmpty(dictDatas))
        {
            DictUtils.setDictCache(dictType, dictDatas);
            return dictDatas;
        }
        return null;
    }
}
